﻿using System;
using System.Diagnostics.Contracts;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class HLinkRecord : WorksheetLevelRecord
    {
        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.HLink; }
        }
        private Guid _hlinkClsid =new Guid("79eac9d0-baf9-11ce-8c82-00aa004ba90b");
        private HyperlinkObject _hyperlink;
        private Ref8U _ref8;

        public HLinkRecord(Cell cell)
        {
            Contract.Requires(cell != null);
            Contract.Requires(cell.Hyperlink != null);
            RangeAddress address = cell.Address.ToRange();
            this._ref8 = (Ref8U) address;
            this._hyperlink = new HyperlinkObject(cell.Hyperlink);
        }

        public HLinkRecord()
        {
        }


        internal override void Apply(BiffReaderWorksheetContext context)
        {
            RangeAddress ra = (RangeAddress) this._ref8;
            Cell cell = context.Worksheet[ra.TopLeft];
            cell.Hyperlink = _hyperlink.GetHyperlink(cell);
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            var writer = context.Writer;
            this._ref8.Write(writer);
            writer.Write(_hlinkClsid.ToByteArray());
            _hyperlink.Write(writer);
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            var reader = context.Reader;
            _ref8 = new Ref8U();
            _ref8.Read(reader);
            _hlinkClsid = new Guid( reader.ReadBytes(16));
            _hyperlink = new HyperlinkObject();
            _hyperlink.Read(reader);
        }
    }
}